import axios from 'axios';
import md5 from 'blueimp-md5';
import { Notification } from 'element-ui';
import { getLogin } from '@/utils/auth';
import { exportExcel } from '@/utils/exportExcel';
import qs from 'qs';
import store from '@/store';

export async function get(url, params = {}, options = {}) {
  params = _addCommonParams(params);
  // console.log('request api get:', `/api${url}`, params);

  if (params.exportExcel) {
    return exportExcel(url, params, options);
  }

  try {
    const resp = await axios.get(`/api${url}`, { params });
    const { data } = resp;
    // console.log(data);
    return handleResponse({
      type: 'get',
      url,
      data,
    });
  } catch (err) {
    // console.log(err);
    return [false, err];
  }
}

export async function post(url, params = {}, options = {}) {
  // params = _addCommonParams(params)

  if (params.exportExcel) {
    return exportExcel(url, params, options);
  }

  const signParams = _addSign();
  const mrAdmin = JSON.parse(sessionStorage.getItem('mrAdmin')) || {};
  let newParamsWithoutNullStr;
  // 如果登录了，就再头信息里添加id,token
  if (mrAdmin.id) {
    signParams.id = mrAdmin.id;
    signParams.token = mrAdmin.token;
  }

  // console.log('request api post:', `/api${url}`, params);
  if (options === 'contentTypeJson') {
    _setAxiosHeader(signParams, 'contentTypeJson');
    newParamsWithoutNullStr = params;
  } else {
    _setAxiosHeader(signParams);
    newParamsWithoutNullStr = qs.stringify(params, { allowDots: true });
  }
  try {
    const resp = await axios.post(`/api${url}`, newParamsWithoutNullStr);

    // console.log(resp)
    const { data } = resp;

    return handleResponse({
      type: 'post',
      url,
      data,
    });
  } catch (err) {
    // Notification.error(err.message)
    Notification.error({ message: err.message });
    return [false, err];
  }
}

function handleResponse({ type, url, data }) {
  if (data.code === 1) {
    // console.log('request api post result:', `/api${url}`, data);
    return [true, data.data];
  } if (data.code === code.EXPIRE) {
    // 退出登录到login
    store.dispatch(types.LOGOUT);

    return [false, data];
  }
  // Notification.error({message:data.message||'未找到错误信息！'})
  return [false, { ...data, message: data.message || '未返回错误信息！' }];
}


function _addCommonParams(params) {
  params = params || {};

  return params;
}

function _addSign() {
  const timestamp = Date.parse(new Date());
  const signParams = {};
  const { token, uid } = getLogin();
  signParams.device_id = '1.0';
  signParams.os_type = 0;
  signParams.timestamp = timestamp;
  signParams.version = '1.0';
  const urlStr = urlEncode(signParams).substr(1);
  signParams.token = token;
  signParams.uid = uid;
  signParams.sign = md5(`${urlStr}global`);
  // console.log(urlStr)

  return signParams;
}

function _setAxiosHeader(headers, contentTypeJson) {
  const axiosCommom = axios.defaults.headers.common || {};
  axios.defaults.headers.common = Object.assign(axiosCommom, headers);
  axios.defaults.headers.timeout = 20000;
  if (contentTypeJson === 'contentTypeJson') {
    axios.defaults.headers['Content-Type'] = 'application/json';
  } else {
    axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
  }
}

function urlEncode(param, key, encode) {
  if (param == null) return '';
  let paramStr = '';
  const t = typeof (param);
  if (t == 'string' || t == 'number' || t == 'boolean') {
    paramStr += `&${key}=${(encode == null || encode) ? encodeURIComponent(param) : param}`;
  } else {
    for (const i in param) {
      const k = key == null ? i : key + (param instanceof Array ? `[${i}]` : `.${i}`);
      paramStr += urlEncode(param[i], k, encode);
    }
  }
  return paramStr;
}
